<?php

namespace app\command;

class Day
{
    // 凌晨2点钟的定时任务
    public static function cron()
    {
        // 清空日志文件
        self::clearLog();
    }

    /**
     * 清空日志文件
     */
    private static function clearLog()
    {
        // 删除前30天的日志
        $timestamp = strtotime('-30 day');
        $dirs = base_path() . '/runtime';
        if (!is_dir($dirs)) {
            return;
        }
        $files = scandir($dirs);
        foreach ($files as $filename) {
            if ($filename == '.' || $filename == '..') {
                continue;
            }
            $dirs_lv2 = $dirs . '/' . $filename;
            if (!is_dir($dirs_lv2)) {
                continue;
            }
            $files_lv2 = scandir($dirs_lv2);
            if (in_array($filename, ['log'])) {
                foreach ($files_lv2 as $filename_lv2) {
                    if ($filename_lv2 != '.' && $filename_lv2 != '..') {
                        $file_timestamp_lv2 = filemtime($dirs_lv2 . '/' . $filename_lv2);
                        if ($file_timestamp_lv2 < $timestamp) {
                            unlink($dirs_lv2 . '/' . $filename_lv2);
                        }
                    }
                }
            } elseif ($filename === 'logs') {
                // 自定义Log
                // 删除前2个月日志
                $timestamp2 = strtotime('-2 month');
                self::clearCustomLog($dirs_lv2, $timestamp2);
            }
        }
    }

    protected static function clearCustomLog($logDirs, $timestamp)
    {
        if (!is_dir($logDirs)) {
            return;
        }
        $files = scandir($logDirs);
        foreach ($files as $filename) {
            if ($filename == '.' || $filename == '..') {
                continue;
            }
            $dirs_lv2 = $logDirs . '/' . $filename;
            if (!is_dir($dirs_lv2)) {
                continue;
            }
            $files_lv2 = scandir($dirs_lv2);
            if (!$files_lv2) {
                continue;
            }
            foreach ($files_lv2 as $filename_lv2) {
                if ($filename_lv2 == '.' || $filename_lv2 == '..') {
                    continue;
                }
                if (date('Ym', $timestamp) == $filename_lv2) {
                    $dirs_lv3 = $dirs_lv2 . '/' . $filename_lv2;
                    $files_lv3 = scandir($dirs_lv3);
                    foreach ($files_lv3 as $filename_lv3) {
                        if ($filename_lv3 != '.' && $filename_lv3 != '..') {
                            unlink($dirs_lv3 . '/' . $filename_lv3);
                        }
                    }
                    // 2个月前的才能删除文件夹
                    rmdir($dirs_lv3);
                }
            }
        }
    }
}